Dashboard Temp Share Shortlinks Frames API

HTMLify

1255. Maximum Score Words Formed by Letters.java
Views: 1 | Author: cody
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
// 1255. Maximum Score Words Formed by Letters java solution
class Solution {
    public int maxScoreWords(String[] words, char[] letters, int[] score) {
        int[] letterCount = new int[26];
        for (char letter : letters) {
            letterCount[letter - 'a']++;
        }
        
        return backtrack(words, letterCount, score, 0);
    }
    
    private int backtrack(String[] words, int[] letterCount, int[] score, int index) {
        if (index == words.length) {
            return 0;
        }
        
        int maxScore = backtrack(words, letterCount, score, index + 1);
        
        int wordScore = 0;
        boolean canForm = true;
        int[] currentLetterCount = new int[26];
        
        for (char c : words[index].toCharArray()) {
            int letterIndex = c - 'a';
            currentLetterCount[letterIndex]++;
            if (currentLetterCount[letterIndex] > letterCount[letterIndex]) {
                canForm = false;
            }
            wordScore += score[letterIndex];
        }
        
        if (canForm) {
            for (int i = 0; i < 26; i++) {
                letterCount[i] -= currentLetterCount[i];
            }
            
            maxScore = Math.max(maxScore, wordScore + backtrack(words, letterCount, score, index + 1));
            
            for (int i = 0; i < 26; i++) {
                letterCount[i] += currentLetterCount[i];
            }
        }
        
        return maxScore;
    }

}